#include "wifiiot_gpio.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "iot_pwm.h"
#include "iot_gpio_pwm.h"
#include "iot_gpio_func.h"


/* GPIO初始化复用为PWM功能 */
u32 GpioInitPwm(u32 pin)
{
    /* 根据输入参数GPIO引脚号初始化 */
    u32 ret = IoTGpioInit(pin);
    if(ret != KP_ERR_SUCCESS){ 
        IOT_PRINTF_FUNC("IoTGpioInit failed :%#x \r\n", ret);
        return ret;
    }

    /* 根据引脚号确定引脚PWM功能配置值及PWM端口号 */
    u8 pwmFunc = 0;
    u32 pwmPort = 0;
    ret = Gpio2Pwm(pin, &pwmFunc, &pwmPort);
    if(ret != KP_ERR_SUCCESS){ 
        IOT_PRINTF_FUNC("Gpio2Pwm failed :%#x \r\n", ret);
        return ret;
    }

    /* 设置复用为PWM功能 */
    ret = IoTGpioSetFunc(pin, pwmFunc);
    if(ret != KP_ERR_SUCCESS){ 
        IOT_PRINTF_FUNC("IoTGpioSetFunc failed :%#x \r\n", ret);
        return ret;
    }

    /* PWM初始化 */
    ret = IoTPwmDeinit(pwmPort);
    if(ret != KP_ERR_SUCCESS){ 
        IOT_PRINTF_FUNC("IoTPwmDeinit failed :%#x \r\n", ret);
        return ret;
    }
    
    ret = IoTPwmInit(pwmPort);
    if(ret != KP_ERR_SUCCESS){ 
        IOT_PRINTF_FUNC("IoTPwmInit failed :%#x \r\n", ret);
        return ret;
    }
    
    return KP_ERR_SUCCESS;
}

/* PWM控制 */
u32 GpioCtrlPwm(u32 pwmPort, u32 state, u16 duty, u32 freq)
{
    u32 ret = KP_ERR_SUCCESS;
    
    switch (state) {
        case PWM_OUT_START:
        {
           /* PWM控制启动 */
            ret = IoTPwmStart(pwmPort, duty, freq);
            if(ret != KP_ERR_SUCCESS){ 
                IOT_PRINTF_FUNC("IoTPwmStart failed :%#x \r\n", ret);
                return ret;
            }
            break;
        }
        case PWM_OUT_STOP:
        {
            /* PWM控制停止 */
            ret = IoTPwmStop(pwmPort);
            if(ret != KP_ERR_SUCCESS){ 
                IOT_PRINTF_FUNC("IoTPwmStop failed :%#x \r\n", ret);
                return ret;
            }
            break;
        }
        default:
        {
            IOT_PRINTF_FUNC("Invalid state :%d \r\n", state);
            return KP_ERR_FAILURE;
        }
    }

    return KP_ERR_SUCCESS;
}

